﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using Ebiz.libs;
using System.Web.Script.Services;
using System.Web.Services;

namespace Ebiz
{
    public partial class Channels : System.Web.UI.Page
    {
        public string tableList = "";
        public string ErrMsg = "";
        public enum UpdateMode{
            Insert, Update, Delete
        }
        protected void Page_Load(object sender, EventArgs e){
            if (!IsPostBack){
                tableList = LoadChannel();
            }
            else if (IsPostBack){
                UpdateMode uMode = new UpdateMode();
                string eMode = hMode.Value;
                switch (eMode){
                    case "INSERT":
                        uMode = UpdateMode.Insert;
                        break;
                    case "UPDATE":
                        uMode = UpdateMode.Update;
                        break;
                    case "DELETE":
                        uMode = UpdateMode.Delete;
                        break;
                }

                string IDChannel = txtCode.Text;
                string CHName = txtName.Text;
                int IDLen = IDChannel.Length;
                if (IDLen < 3 || IDLen > 3){
                    ErrMsg = "ID Channel must be 3 characters";
                }else{
                    string updateResult = UpdateChannel(IDChannel, CHName, uMode);
                    if (updateResult == "success"){
                        Response.Redirect("Channels.aspx", true);
                    }else{
                        if (updateResult == "failed"){
                            ErrMsg = "Update failed!";
                            Response.Write("<script>alert('Update failed!'); window.location.href='Channels.aspx'</script>");
                        }else{
                            string errMessage = "Update failed: " + updateResult;
                            ErrMsg = errMessage;
                            Response.Write("<script>alert('Update failed!'); window.location.href='Channels.aspx'</script>");
                        }
                    }
                }
            }
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string UpdateChannel(string ChannelCode, string ChannelName, 
            UpdateMode Mode){

            string result = "";
            SqlConnection cn = new SqlConnection(DBUtilities.strConnection("devCon"));
            using (cn){
                cn.Open();

                string qry = "";
                Dictionary<string, object> dctSql = new Dictionary<string, object>();
                switch (Mode){
                    case UpdateMode.Insert:
                        qry = "INSERT INTO mstChannel (IDChannel, ChannelName) VALUES (@IDChannel, @ChannelName)";
                        dctSql.Add("@IDChannel", ChannelCode.ToUpper());
                        dctSql.Add("@ChannelName", ChannelName);
                        break;
                    case UpdateMode.Update:
                        qry = "UPDATE mstChannel SET ChannelName = @ChannelName " +
                            "WHERE IDChannel = @IDChannel";
                        dctSql.Add("@IDChannel", ChannelCode);
                        dctSql.Add("@ChannelName", ChannelName);
                        break;
                    case UpdateMode.Delete:
                        qry = "DELETE mstChannel WHERE IDChannel = @IDChannel";
                        dctSql.Add("@IDChannel", ChannelCode);
                        break;
                }

                SqlCommand cmd = new SqlCommand(qry, cn);
                foreach (KeyValuePair<string, object> kvp in dctSql){
                    cmd.Parameters.AddWithValue(kvp.Key, kvp.Value);
                }

                try{
                    int affectedFields = cmd.ExecuteNonQuery();
                    if (affectedFields > 0){
                        result = "success";
                    }else{
                        result = "failed";
                    }
                }catch (SqlException ex){
                    string errMsg = ex.Message;
                    result = errMsg;
                }finally{
                    cn.Close();
                }
            }
            return result;
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static List<object> DeleteChannel(string ChannelCode) {

            List<object> result = new List<object>();

            string dbName = DBUtilities.GetDBName("devCon");
            string query = "UPDATE " + dbName + ".dbo.mstChannel SET StatusCode = '104' WHERE " +
                "(IDChannel = @IDChannel)";
            Dictionary<string, object> dctParams = new Dictionary<string, object>();
            dctParams.Add("@IDChannel", ChannelCode);
            Dictionary<string, object> ExecQry = DBUtilities.ExecQuery(query, dctParams, DBUtilities.QueryMode.Write);
            if ((int)ExecQry["Status"] > 0){
                result.Add(1);
                result.Add((string) ExecQry["Content"]);
            }else{
                result.Add(0);
                result.Add((string)ExecQry["Content"]);
            }
            return result;
        }

        private static string LoadChannel(){
            string result = "";
            SqlConnection cn = new SqlConnection(DBUtilities.strConnection("devCon"));
            using (cn){
                cn.Open();

                string qry = "SELECT IDChannel, ChannelName FROM mstChannel WHERE " +
                    "(StatusCode = '101')";

                SqlCommand cmd = new SqlCommand(qry, cn);
                SqlDataReader rdr = cmd.ExecuteReader();
                if (rdr.HasRows){
                    int idx = 0;
                    string imgDel = "<img class='btnView' src='images/info.png' title='Details' alt='Details' style='border:0;width:14px;height:14px;' />";
                    while (rdr.Read()){
                        string sKey = rdr.GetValue(0).ToString();
                        string sVal = rdr.GetValue(1).ToString();

                        string trClass = ((idx % 2) == 0) ? " class='odd' " : " class='even' ";

                        string tRow = "<tr " + trClass + "style='text-align:left;'><td>" + sKey + "</td>";
                        tRow += "<td style='text-align:left;'>" + sVal + "</td>";
                        tRow += "<td style='text-align:center;'>" + imgDel + "</td></tr>";

                        result += tRow;

                        idx++;
                    }
                }
                cn.Close();
            }
            return result;
        }
    }
}